package com.economy.swefunds;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SearchActivity extends Activity {
	
	public static final int STATE_GETTING_FIRST_PAGE = 0;
	public static final int STATE_GETTING_NEXT_PAGE = 1;
	
	private int ActivityState = -1;
	private int currentPage = -1;
	private int nrPages = -1;
	
	private String xPathPageLookup = "//table[2]//font"; //get pages
	private String xPathExpression = "//table[1]//tr/td/a"; //get funds
	
	private ArrayList<String> SearchNameList;
	private ArrayList<String> SearchIdList;
	
	PortfolioList Portfolio;
	
	private ListView FundListView;
	private ArrayAdapter<String> fundsAdapter;
	private ProgressDialog progress;
	
	private UrlLoader urlLoader;
	private URL searchUrl;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fund_search);
        
        Portfolio = PortfolioList.getInstance(getApplicationContext());
        
        SearchNameList = new ArrayList<String>();
        SearchIdList = new ArrayList<String>();
        
        fundsAdapter = new ArrayAdapter<String>(this, R.layout.fundlist, SearchNameList);
        
        FundListView = (ListView)findViewById(R.id.fundList);
        FundListView.setTextFilterEnabled(true);        
        FundListView.setAdapter(fundsAdapter);
        
        final TextView searchBox = (TextView)findViewById(R.id.searchFundBox);
        
        // Searchbutton and action
        ImageButton searchButton = (ImageButton)findViewById(R.id.searchFundButton);
        searchButton.setOnClickListener(new View.OnClickListener()  {
			@Override
			public void onClick(View v) {
				if (searchBox.getText().length() != 0) {
	    			SearchIdList.clear();
	    			SearchNameList.clear();
					SearchFund(searchBox.getText().toString());
				}
			}
		});
        
		FundListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> a, View v, int pos, long id) {
				Object o = a.getAdapter().getItem(pos);
				String fund = o.toString();
				String fundId = SearchIdList.get(pos).toString(); 
				Portfolio.addFund(fund, fundId);
				Toast.makeText(getApplicationContext(), "You have added: " + fund, Toast.LENGTH_SHORT).show();
				return true;
			}
		});
			
        //Lista fonder på ID och namn:
        /*  http://customer.mseu.net/SE/finansportalen/comparefund/index.asp?lang=SV&mec='NTOCT01107','0P00000H58','CL00012073'&FundName='Carlson%20Realr%E4ntefond','Nordea%20Realr%E4ntefond','Skandia%20Realr%E4ntefond'
         */
    }
    public void SearchFund(String searchWord) {
    	if (searchWord.length() == 0) {
    		return;
    	}
    	// Show progress dialog
    	progress = ProgressDialog.show(this, "Searching...", "Parsing funds data");
    	
		searchUrl = null;
		try {
			searchUrl = new URL("http://customer.mseu.net/SE/finansportalen/lookup/result.asp?cat=-1&search="
					+ URLEncoder.encode(searchWord, "utf-8") + "&page=");
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
    	ActivityState = STATE_GETTING_FIRST_PAGE;
		urlLoader = new UrlLoader(handler);
		// Start urlLoader thread and wait for handleMessage-callback on given handler
    	urlLoader.loadUrl(searchUrl);
    }
    
    // UrlLoader thread callback
    private Handler handler = new Handler() {
    	
    	private ArrayList<Object[]> pages = null;
    	
    	private void addPages() {
    		// loop through all pages
    		for (Object[] o: pages) {
    			for (Object t: o) {
    				// string is now the following:
    				// "javaScript:doSendOverCompare('F0NDID','Fondnamnet');"
    				String fundStr = ((TagNode)t).getAttributeByName("href");
    				String delimiter = "\\'";
    				String[] fundStrSplit;
    				fundStrSplit = fundStr.split(delimiter);

    				if (fundStrSplit.length > 3) {
    					String fundId = fundStrSplit[1];
    					String fundName = fundStrSplit[3];
    					SearchIdList.add(fundId);
    					SearchNameList.add(fundName);
    				}
    			}
    		}
    		if (SearchIdList.size() != SearchNameList.size()) {
    			// Illegal
    			SearchIdList.clear();
    			SearchNameList.clear();
    			Log.w("WARNING", "Fund Names and Ids does not match");
    		}
    		String toastMsg;
    		if (SearchNameList.size() > 0) {
    			fundsAdapter.notifyDataSetChanged();
    			toastMsg = "Long click to add fund to your portfolio";
    		}
    		else
    			toastMsg = "No funds found";
    		Toast.makeText(getApplicationContext(), toastMsg, Toast.LENGTH_LONG).show();
    		progress.dismiss();
    	}
    	
    	// UrlLoader callback when a page is fully loaded
    	public void handleMessage(Message msg) {
    		
    		if (msg.what == UrlLoader.CONNECTION_TIMEOUT) {
    			Toast.makeText(getApplicationContext(), "Connection timed out", Toast.LENGTH_LONG).show();
        		progress.dismiss();
        		ActivityState = -1;
        		return;
    		}
    		
    		if (ActivityState == STATE_GETTING_FIRST_PAGE) { 
    			TagNode node = urlLoader.getPage();
    			try {
    				Object[] pageNodes = node.evaluateXPath(xPathPageLookup);
    				pages = new ArrayList<Object[]>();

    				Object[] fundNodes = node.evaluateXPath(xPathExpression);
    				pages.add(fundNodes);

    				nrPages = pageNodes.length;
    				if (nrPages > 1) {
    					// add the rest of pages
    					if (nrPages > 6)
    						nrPages = 6; // limit results
    					currentPage = 2;
    					URL pageUrl = null;
    					try { 
    						pageUrl = new URL(searchUrl.toString() + (currentPage)); }
    					catch (MalformedURLException e) { e.printStackTrace();	}
    					ActivityState = STATE_GETTING_NEXT_PAGE;
    					urlLoader.loadUrl(pageUrl);
    				}
    				else {
    					addPages();
    				}

    			} catch (XPatherException e) {
    				Log.e("ERROR", e.getMessage());
    			}
    		}
    		
    		else if (ActivityState == STATE_GETTING_NEXT_PAGE) {
    			progress.setProgress(80);
    			TagNode node = urlLoader.getPage();
				Object[] fundNodes = null;
				try { // TODO: Fixa alla jävla try catch (lägg dom över större spann och fixa typerna)
					fundNodes = node.evaluateXPath(xPathExpression);
				} catch (XPatherException e1) {
					e1.printStackTrace();
				}
				pages.add(fundNodes);
				currentPage++;
				if (currentPage < nrPages) {
					URL pageUrl = null;
					try { 
						pageUrl = new URL(searchUrl.toString() + (currentPage)); }
					catch (MalformedURLException e) { e.printStackTrace();	}
					ActivityState = STATE_GETTING_NEXT_PAGE;
					urlLoader.loadUrl(pageUrl);
				}
				else {
					addPages();
				}
    		}
				
        }
    	
    };
}